/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Manager;

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Nguyen Van Duoc
 */
public class MailManager {
    public void send(String to, String subject, String content) throws MessagingException {
        final String accName = "thanhnamvt2011@gmail.com";
        final String accPassword = "gg291095vt";
        
        Properties props = System.getProperties();

        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", true);

        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(accName, accPassword);
            }
        });
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(accName));
        msg.setRecipients(RecipientType.TO, InternetAddress.parse(to, false));
        msg.setSubject(subject);
        msg.setText(content);

        Transport.send(msg);
    }
    
    public static void receive() throws MessagingException {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props, null);
        
        Store store = session.getStore("pop3");
        store.connect("testworkvt2014@gmail.com", "291095vungtau");
        Folder folder = store.getDefaultFolder();
        if(folder != null) {
            folder = folder.getFolder("Inbox");
        }
        Message[] msgs = folder.getMessages();
        System.out.println(msgs.length);
    }
    
    public static void main(String[] args) throws MessagingException {
        receive();
    }
}
